<template>
  <div class="search">
    <van-nav-bar
        title="搜索"
        left-arrow
        @click-left="onClickLeft"
    />
    <van-search
        v-model="value"
        autofocus
        shape="round"
        placeholder="请输入搜索关键词"
        @blur="onSearch"
    />
    <p>历史记录</p>
    <ul class="historyList">
      <li v-for="(item,index) in $store.state.userInfo.historyList" :key="index">
        <span @click="value = item">{{item}}<van-icon name="cross" @click.self="removeHistory(index)" style="padding-left: 5px" /></span>
      </li>
    </ul>
    <p>推荐商品 / 搜索结果</p>
    <div v-if="showFlag">
      <van-skeleton :row="2" v-for="num in 10" :key="num" style="padding: 10px 30px"/>
    </div>
    <div v-else>
      <SearchList :total="total" @changePage="getPageNum" :searchList="searchList" v-if="searchList.length != 0"></SearchList>
      <van-empty v-else image="search" description="暂无商品" />
    </div>

  </div>
</template>

<script>
import {getGoodsList} from "@/api/api";
import SearchList from "@/components/Search/SearchList";

export default {
name: "Search",
  data() {
    return {
      value: '',
      searchList:[],
      total:0,
      pageNum:1,
      showFlag:true,
    };
  },
  components:{
    SearchList
  },
  methods:{
    onClickLeft(){
      this.$router.go(-1)
    },
    onSearch(){
      if(this.value){
        this.$store.commit('addHistory',this.value)
      }
    },
    removeHistory(index){
      this.$store.commit('removeHistory',index)
    },
    getPageNum(data){
      this.pageNum = data
    },
    getSearchList(){
      getGoodsList(this.value,this.pageNum).then(res=>{
        if(res.data.rows){
          console.log(res)
          this.searchList = res.data.rows
          this.total = res.data.total
          this.showFlag = false
        }else(
            this.searchList = []
        )
      })
    }
  },
  created() {
    this.getSearchList()
  },
  watch:{
  value(){
    this.getSearchList()
  },
    pageNum(){
      this.getSearchList()
    }
  }
}
</script>

<style scoped lang="less">
.search{
  >p{
    margin: 10px 5px;
    padding: 0 10px;
    border-left: 5px solid #e51c23;
    font-weight: bold;
    font-size: 16px;
  }
}
.historyList>{
  padding: 10px 20px;
  overflow: hidden;
  >li{
    float: left;
    margin: 10px;
    >span{
      //width: 30px;
      height: 20px;
      padding: 5px 10px;
      background-color: rgba(221,221,221,.5);
      border-radius: 20px;
    }
  }
}

</style>